<template>
  <div>
    <input v-model="keyword" @change="search" />
    <van-tree-select
      height="55vw"
      :items="items"
      :main-active-index.sync="active"
      @click-nav="clickHandler"
    >
      <template #content>
        <div v-if="flag">
          <div v-for="item in selected_items" :key="item.id">
            {{item.title}}
            <br />
            <img :src="item.image" />
            <span v-show="item.cartnum>=1">
              <button @click="REMOVE_CART(item)">-</button>
              {{item.cartnum}}
            </span>
            <button @click="ADD_CART(item)">+</button>
          </div>
        </div>
      </template>
    </van-tree-select>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
  computed: {
    ...mapState(["dish_list", "flag"]),
  },
  methods: {
    ...mapMutations(["ADD_CART", "REMOVE_CART"]),
    search() {
      // 重置为搜索前的数据
      this.selected_items = [...this.all_items];

      // 进行搜索操作
      this.selected_items = this.selected_items.filter((item) => {
        if (!this.keyword) {
          return true;
        } else {
          return item.title.includes(this.keyword);
        }
      });
    },

    // 处理标签点击事件
    clickHandler(index) {
      console.log("click handler ", index);

      this.selected_items = this.dish_list[Object.keys(this.dish_list)[index]];

      // 获取当前分类下所有的数据
      this.all_items = [...this.selected_items];
    },

    // 遍历菜品列表的key值 ，构造this.items数据
    initData() {
      // 当flag为true时说明 dish_list的值拿到了，再处理后续
      if (this.flag) {
        // 对数组遍历
        Object.keys(this.dish_list).forEach((key) => {
          this.items.push({ text: key, badge: this.dish_list[key].length });
        });

        // 设置选中tab的默认列表
        this.selected_items = this.dish_list[Object.keys(this.dish_list)[0]];
       

        // 获取当前分类下所有的数据
        this.all_items = [...this.selected_items];
      }
    },
  },
  watch: {
    // 监控菜品列表是否渲染
    flag() {
      this.initData();
    },
  },
  data() {
    return {
      keyword: "",
      active: 0,
      items: [],
      selected_items: [],
      all_items: [],
    };
  },
  created() {
    console.log("created dish ");
    this.initData();
  },
};
</script>